package ing.gzq.model;


import ing.gzq.websocket.WebSocket;
import lombok.Data;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Data
public class Room {

    static Log log = LogFactory.getLog(Room.class);


    private Long id;

    private String teacherId;

    private WebSocketSession teacherSession;

    private Map<String, WebSocketSession> students = new ConcurrentHashMap<>();

    public Room(Long id, String teacherId, WebSocketSession teacherSession) {
        this.id = id;
        this.teacherId = teacherId;
        this.teacherSession = teacherSession;
    }

    public void addStudent(String studentId, WebSocketSession socketSession) {
        students.put(studentId, socketSession);
    }


    public void removeStudent(String studentId) {
        students.remove(studentId);
    }

    public void sendToTeacher(String message) throws IOException {
        if(teacherSession == null) {
            log.info("send to teacher : teacherSession is null "+message);
            return;
        }
        teacherSession.sendMessage(new TextMessage(message));
        log.info("send to teacher :"+message);
    }


    public void sendToStudents(String message) throws IOException {
        for (Map.Entry<String, WebSocketSession> entry : students.entrySet()) {
            String key = entry.getKey();
            entry.getValue().sendMessage(new TextMessage(message));
            log.info("send to "+key+":"+message);
        }
    }


    public void sendToStudent(String target, String message) throws IOException {
        if (students.containsKey(target)) {
            students.get(target).sendMessage(new TextMessage(message));
            log.info("send to student:"+message);
        }
    }


    public void sendToAll(String message) throws IOException {
        sendToTeacher(message);
        sendToStudents(message);
        log.info("send to all :"+message);
    }

    public void sendToTarget(String target, String message) throws IOException {
        if (Objects.equals(target,getTeacherId())) {
            sendToTeacher(message);
            log.info("send to target in teacher :"+message);
        } else {
            sendToStudent(target, message);
            log.info("send to target in student :"+message);
        }
    }
}
